/**
 * Created by liuhe on 2016/12/16.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
//引入model
const config_order_model_1 = require("../dao/configOrder/config-order-model");
const zlib_util_1 = require("@qianmi/x-site-common/util/zlib-util");
const Immutable = require("immutable");
const const_common_1 = require("@qianmi/x-site-common/const-common");
let configOrderFilePath = const_common_1.constCommon.ossPath.pageConfigOrder;
class ConfigOrderService {
    constructor(ossClient) {
        this.ossClient = ossClient;
    }
    /**
       * 查询获取 configOrder 数据库拿不到数据 就去 阿里云 拿  阿里云拿不到 就抛异常
       * @param env
       * @param uid
       * @param systemCode
       * @param platform
       * @param pageType
       * @param pageCode
       * @returns {Promise}
       */
    async getConfigOrder({ env, uid, systemCode, platform, pageType, pageCode }) {
        let configOrder = await new Promise((resolve, reject) => {
            config_order_model_1.default.findOne({
                uid,
                systemCode,
                platform,
                pageType,
                pageCode
            })
                .lean()
                .exec(function (err, data) {
                data && data.configOrder ? resolve(data.configOrder) : err ? reject(err) : resolve(null);
            });
        });
        if (!configOrder) {
            //从阿里云获取文件
            let _configOrderFilePath = configOrderFilePath
                .replace('${env}', env)
                .replace('${systemCode}', systemCode)
                .replace('${userId}', uid)
                .replace('${platForm}', platform)
                .replace('${pageCode}', pageCode);
            try {
                let response = await this.ossClient.getObjectAbsolute(_configOrderFilePath);
                if (response.res.status === 200) {
                    configOrder = await zlib_util_1.unzip(response.content.toString());
                    configOrder = JSON.parse(configOrder);
                }
                //针对商品列表页面做 兼容处理
                if (pageType == 'goodsList') {
                    configOrder = _cleanAjaxData(configOrder);
                }
                await this.upsertConfigOrder({
                    uid,
                    systemCode,
                    platform,
                    pageType,
                    pageCode,
                    configOrder
                });
            }
            catch (err) {
                //提供默认数据
                configOrder = null;
            }
        }
        return configOrder;
    }
    /**
       * 保存configOrder  有则改之 无则加之
       * @param uid
       * @param systemCode
       * @param platform
       * @param pageType
       * @param pageCode
       * @param configOrder
       * @returns {Promise}
       */
    upsertConfigOrder({ uid, systemCode, platform, pageType, pageCode, configOrder }) {
        let target = { uid, systemCode, platform, pageType, pageCode };
        let result = { uid, systemCode, platform, pageType, pageCode, configOrder };
        return new Promise((resolve, reject) => {
            config_order_model_1.default.update(target, result, { upsert: true }).exec(function (err, data) {
                err ? reject(err) : resolve(data);
            });
        });
    }
    /**
       * 删除当前的configOrder
       * @param uid
       * @param systemCode
       * @param platform
       * @param pageType
       * @param pageCode
       * @returns {Promise}
       */
    deleteConfigOrder({ uid, systemCode, platform, pageType, pageCode }) {
        return new Promise((resolve, reject) => {
            config_order_model_1.default.findOneAndRemove({ uid, systemCode, platform, pageType, pageCode }, (err, data) => {
                err ? reject(err) : resolve(data);
            });
        });
    }
    /**
       * 批量查找相关用户的所有configOrder的集合 提供给偷天换日使用 避免不停的查询用户的configOrder
       * @param uidArray      eg: ['A123','A234','A345','A456',...]
       * @param systemCode    eg: 'd2cStore'
       * @param platform
       * @param pageTypeArray eg: ['index','poster','goodsList']
       */
    getConfigOrdersList({ uidArray, systemCode, platform, pageTypeArray }) {
        return new Promise((resolve, reject) => {
            config_order_model_1.default.find({
                uid: { $in: uidArray },
                systemCode,
                platform,
                pageType: { $in: pageTypeArray }
            }, {
                _id: 0,
                __v: 0
            })
                .lean()
                .exec((err, data) => {
                err ? reject(err) : resolve(data);
            });
        });
    }
}
exports.default = ConfigOrderService;
/**
 * 删除已经上传阿里云的configOrder中的桩数据
 * @param configOrder
 * @returns {*}
 */
function _cleanAjaxData(configOrder) {
    configOrder = Immutable.fromJS(configOrder);
    let __infoPath = [];
    treeConfig({
        configOrder,
        hitCompCalBack: (widgetConfig, pathArray) => {
            if (widgetConfig.get('widgetNameSpace') == 'x-site-ui-server/goods-list/condition-filter/mi/mi-goodsList-filter-bar') {
                __infoPath.push(pathArray.push('props').toJS());
            }
        }
    });
    for (let i = 0, len = __infoPath.length; i < len; i++) {
        configOrder = configOrder.deleteIn(__infoPath[i]);
    }
    return configOrder.toJS();
}
function treeConfig({ configOrder, hitCompCalBack, pathArray = Immutable.List() }) {
    hitCompCalBack && hitCompCalBack(configOrder, pathArray);
    if (!configOrder) {
        throw new Error(`对应路径配置为空::${pathArray.join(',')}`);
    }
    if (configOrder.has('children') && configOrder.get('children').count() > 0) {
        configOrder.get('children').forEach((subWidgetTreeConfig, index) => {
            return treeConfig({
                configOrder: subWidgetTreeConfig,
                hitCompCalBack,
                pathArray: pathArray.push('children').push(index)
            });
        });
    }
}
